/**************************************

    author  : xy_god
    e-mail  : xy_god@thesct.net
    homepage: http://www.thesct.net

    FileName: xthread.c
    gen_time: 2014.10.13

    comments:
        该文件定义了xthread的相关函
    数.

 **************************************/

#include "xthread.h"

//-------------------------------- start --------------------------------

// 传递给POSIX线程参数的类型
typedef struct x_targs
{
  x_thread_func_t p_tfunc;
  void *args;
}x_targs_t;

// pthread线程入口点
void* pthread_func(void *args)
{
  int i_err = 0;
  void *p_ret = NULL;
  x_targs_t *p_args;

  p_args = (x_targs_t*)args;
  
  x_mem_pool_t *p_mp = NULL;
  p_mp = create_mem_pool(&i_err);
  if (p_mp == NULL) {
    printf("main函数中，执行create_mem_pool后发生错误!错误号：%d.\r\n", i_err);
    goto error_tray;
  }

  x_local_obj_t local_obj;
  local_obj.p_mp = p_mp;
  
  p_ret = p_args->p_tfunc(&local_obj, p_args->args);

  // 普通退出
  if (local_obj.p_mp != NULL) {
	destroy_mem_pool(local_obj.p_mp);
  }
  return p_ret;
 error_tray:
  if (local_obj.p_mp != NULL) {
	destroy_mem_pool(local_obj.p_mp);
  }
  return p_ret;
}

// 创建线程
int create_thread(pthread_t *thread, const pthread_attr_t *attr,
				  x_thread_func_t thread_func, void *args)
{
  int i_ret = 0;
  x_targs_t targs;
  targs.p_tfunc = thread_func;
  targs.args = args;
  i_ret = pthread_create(thread, attr, pthread_func, &targs);
  return i_ret;
}

//--------------------------------  end  --------------------------------
